<template>
  <div class="channel-list">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索通道名称"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="refreshChannels" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新通道
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-row">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-statistic title="总通道数" :value="totalChannels" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="活跃通道" :value="activeChannels" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="启用通道" :value="enabledChannels" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="禁用通道" :value="disabledChannels" />
        </el-col>
      </el-row>
    </div>

    <!-- 通道列表 -->
    <el-table
      :data="filteredChannels"
      v-loading="loading"
      stripe
      style="width: 100%"
      empty-text="暂无通道数据"
    >
      <el-table-column prop="name" label="通道名称" width="150" />
      <el-table-column prop="channelNo" label="通道号" width="80" />
      <el-table-column prop="profileToken" label="配置文件" width="120" show-overflow-tooltip />
      <el-table-column prop="rtspUrl" label="RTSP地址" min-width="200" show-overflow-tooltip />
      <el-table-column label="分辨率" width="120">
        <template #default="{ row }">
          {{ row.videoWidth && row.videoHeight ? `${row.videoWidth}x${row.videoHeight}` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="videoEncoding" label="编码格式" width="100" />
      <el-table-column prop="frameRate" label="帧率" width="80">
        <template #default="{ row }">
          {{ row.frameRate ? `${row.frameRate}fps` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="enabled" label="启用状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.enabled"
            @change="toggleChannel(row)"
            :loading="row.switching"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group size="small">
            <el-button @click="viewChannel(row)">查看</el-button>
            <el-button @click="editChannel(row)">编辑</el-button>
            <el-button @click="testChannel(row)" :loading="row.testing">测试</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 通道详情对话框 -->
    <el-dialog v-model="channelDetailVisible" :title="currentChannel?.name || '通道详情'" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="通道名称">{{ currentChannel?.name }}</el-descriptions-item>
        <el-descriptions-item label="通道号">{{ currentChannel?.channelNo }}</el-descriptions-item>
        <el-descriptions-item label="配置文件">{{ currentChannel?.profileToken }}</el-descriptions-item>
        <el-descriptions-item label="RTSP地址" :span="2">
          <el-input :value="currentChannel?.rtspUrl" readonly />
        </el-descriptions-item>
        <el-descriptions-item label="分辨率">
          {{ currentChannel?.videoWidth && currentChannel?.videoHeight ? `${currentChannel.videoWidth}x${currentChannel.videoHeight}` : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="编码格式">{{ currentChannel?.videoEncoding || '-' }}</el-descriptions-item>
        <el-descriptions-item label="帧率">{{ currentChannel?.frameRate ? `${currentChannel.frameRate}fps` : '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentChannel?.status)">
            {{ getStatusLabel(currentChannel?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="启用状态">
          <el-tag :type="currentChannel?.enabled ? 'success' : 'danger'">
            {{ currentChannel?.enabled ? '已启用' : '已禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(currentChannel?.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(currentChannel?.updatedAt) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="channelDetailVisible = false">关闭</el-button>
        <el-button type="primary" @click="editChannel(currentChannel)">编辑</el-button>
      </template>
    </el-dialog>

    <!-- 编辑通道对话框 -->
    <el-dialog v-model="channelEditVisible" :title="isEditing ? '编辑通道' : '添加通道'" width="50%">
      <el-form :model="editingChannel" :rules="channelRules" ref="channelFormRef" label-width="100px">
        <el-form-item label="通道名称" prop="name">
          <el-input v-model="editingChannel.name" placeholder="请输入通道名称" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="editingChannel.enabled" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editingChannel.description"
            type="textarea"
            :rows="3"
            placeholder="请输入通道描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="channelEditVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChannel" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import * as channelApi from '@/api/channel'
import { formatRelativeTime, debounce } from '@/utils/common'

// Props
const props = defineProps({
  deviceId: {
    type: String,
    required: true
  },
  deviceName: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['close'])

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const searchKeyword = ref('')
const channels = ref([])

// 通道详情
const channelDetailVisible = ref(false)
const currentChannel = ref(null)

// 编辑通道
const channelEditVisible = ref(false)
const isEditing = ref(false)
const editingChannel = ref({
  name: '',
  enabled: true,
  description: ''
})
const channelFormRef = ref()

// 表单验证规则
const channelRules = {
  name: [
    { required: true, message: '请输入通道名称', trigger: 'blur' }
  ]
}

// 计算属性
const filteredChannels = computed(() => {
  if (!searchKeyword.value) {
    return channels.value
  }
  return channels.value.filter(channel => 
    channel.name?.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const totalChannels = computed(() => channels.value.length)
const activeChannels = computed(() => channels.value.filter(c => c.status === 'ACTIVE').length)
const enabledChannels = computed(() => channels.value.filter(c => c.enabled).length)
const disabledChannels = computed(() => channels.value.filter(c => !c.enabled).length)

// 方法
const loadChannels = async () => {
  try {
    loading.value = true
    const response = await channelApi.getChannelsByDeviceIdString(props.deviceId)
    channels.value = response || []
  } catch (error) {
    console.error('加载通道列表失败:', error)
    ElMessage.error('加载通道列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const refreshChannels = async () => {
  try {
    loading.value = true
    await channelApi.refreshChannelsByDevice(props.deviceId)
    await loadChannels()
    ElMessage.success('通道刷新成功')
  } catch (error) {
    console.error('刷新通道失败:', error)
    ElMessage.error('刷新通道失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const viewChannel = (channel) => {
  currentChannel.value = channel
  channelDetailVisible.value = true
}

const editChannel = (channel) => {
  isEditing.value = true
  editingChannel.value = {
    id: channel.id,
    name: channel.name,
    enabled: channel.enabled,
    description: channel.description || ''
  }
  channelEditVisible.value = true
}

const saveChannel = async () => {
  try {
    await channelFormRef.value.validate()
    saving.value = true
    
    if (isEditing.value) {
      await channelApi.updateChannel(editingChannel.value.id, editingChannel.value)
      ElMessage.success('通道更新成功')
    }
    
    channelEditVisible.value = false
    await loadChannels()
  } catch (error) {
    if (error.message) {
      ElMessage.error('保存失败: ' + error.message)
    }
  } finally {
    saving.value = false
  }
}

const toggleChannel = async (channel) => {
  try {
    channel.switching = true
    await channelApi.toggleChannelEnabled(channel.id, { enabled: channel.enabled })
    ElMessage.success(channel.enabled ? '通道已启用' : '通道已禁用')
  } catch (error) {
    channel.enabled = !channel.enabled // 回滚状态
    ElMessage.error('操作失败: ' + error.message)
  } finally {
    channel.switching = false
  }
}

const testChannel = async (channel) => {
  try {
    channel.testing = true
    const result = await channelApi.testChannelConnection(channel.id)
    if (result.success) {
      ElMessage.success('通道连接正常')
    } else {
      ElMessage.warning('通道连接失败: ' + result.message)
    }
  } catch (error) {
    ElMessage.error('测试失败: ' + error.message)
  } finally {
    channel.testing = false
  }
}

const getStatusType = (status) => {
  switch (status) {
    case 'ACTIVE': return 'success'
    case 'INACTIVE': return 'warning'
    case 'ERROR': return 'danger'
    default: return 'info'
  }
}

const getStatusLabel = (status) => {
  switch (status) {
    case 'ACTIVE': return '活跃'
    case 'INACTIVE': return '非活跃'
    case 'ERROR': return '错误'
    default: return '未知'
  }
}

const formatTime = (time) => {
  return time ? formatRelativeTime(time) : '-'
}

// 搜索防抖
const handleSearch = debounce(() => {
  // 搜索逻辑已在计算属性中处理
}, 300)

// 生命周期
onMounted(() => {
  loadChannels()
})

// 监听设备ID变化
watch(() => props.deviceId, () => {
  if (props.deviceId) {
    loadChannels()
  }
})
</script>

<style scoped>
.channel-list {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-row {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.el-statistic {
  text-align: center;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>